package com.exam.pay_local_sign.wxpay;

import android.app.Activity;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

/**
 * 微信支付工具类
 */
public class WXPayUtil {
    /**
     * 微信支付(后端签名)
     */
    public static void wxPay(Activity activity, WXOrderInfo wxOrderInfo) {
        //        IWXAPI msgApi = WXAPIFactory.createWXAPI(activity, null);
        //        msgApi.registerApp(Constants.WX_APP_ID);
        //        PayReq req = new PayReq();// 创建支付请求
        //        req.appId = wxOrderInfo.getAppid();
        //        req.partnerId = wxOrderInfo.getPartnerid();
        //        req.prepayId = wxOrderInfo.getPrepayid();
        //        req.packageValue = wxOrderInfo.getWxpackage();
        //        req.nonceStr = wxOrderInfo.getNoncestr();
        //        req.timeStamp = wxOrderInfo.getTimestamp();
        //        req.sign = wxOrderInfo.getSign();
        //        msgApi.sendReq(req);
    }

    /**
     * 微信支付(本地签名)
     */
    public static void wxPaySign(Activity activity, WXOrderInfo wxOrderInfo) {
        //        IWXAPI msgApi = WXAPIFactory.createWXAPI(activity, null);
        //        msgApi.registerApp(Constants.WX_APP_ID);
        //        PayReq req = new PayReq();// 创建支付请求
        //        req.appId = wxOrderInfo.getAppid();
        //        req.partnerId = wxOrderInfo.getPartnerid();
        //        req.prepayId = wxOrderInfo.getPrepayid();
        //        req.packageValue = wxOrderInfo.getWxpackage();
        //        req.nonceStr = wxOrderInfo.getNoncestr();
        //        req.timeStamp = wxOrderInfo.getTimestamp();
        //        // req.sign = wxOrderInfo.getSign();
        //        // LogUtils.s("服务器:" + req.sign);
        //        /********************* 本地签名 *********************/
        //        List<BasicNameValuePair> signParams = new LinkedList<BasicNameValuePair>();
        //        signParams.add(new BasicNameValuePair("appid", req.appId));
        //        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        //        signParams.add(new BasicNameValuePair("package", req.packageValue));
        //        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        //        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        //        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
        //        req.sign = genAppSign(signParams, WXConstants.API_KEY);
        //        /********************* 本地签名 *********************/
        //        msgApi.sendReq(req);
    }

    /**
     * 生成签名
     */
    public static String genAppSign(List<BasicNameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(WXConstants.API_KEY);
        String appSign = MD5.getMessageDigest(sb.toString().getBytes());
        Log.e("orion", appSign);
        return appSign;
    }

    /**
     * 要求外部订单号必须唯一。
     *
     * @return
     */
    private static String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }


    /**
     * 微信统一下单[如果有正确的微信相关key可以本地下单],到子线程运行
     */
    public static String wxUniteOrder() {
        String nonce_str = UUID.randomUUID().toString().replace("-", "");
        String outTradeNo = getOutTradeNo();

        //拼接字段，顺序不能变
        String A = "appid=" + WXConstants.APP_ID +
                "&body=ceshi" +
                "&mch_id=" + WXConstants.MCH_ID +
                "&nonce_str=" + nonce_str +
                "&notify_url=https://wxpay.wxutil.com/pub_v2/app/app_pay.php" +
                "&out_trade_no=" + outTradeNo +
                "&spbill_create_ip=192.168.1.1" +
                "&total_fee=1" +
                "&trade_type=APP";
        String key = WXConstants.API_KEY;
        String temp = A + "&key=" + key;
        // 生成sign
        String sign = MD5.getMessageDigest(temp.getBytes()).toUpperCase();

        //组建xml数据
        //拼接字段，顺序不能变
        StringBuilder xml = new StringBuilder();
        xml.append("<xml>\n");
        xml.append("<appid>" + WXConstants.APP_ID + "</appid>\n");
        xml.append("<body>ceshi</body>\n");
        xml.append("<mch_id>" + WXConstants.MCH_ID + "</mch_id>\n");
        xml.append("<nonce_str>" + nonce_str + "</nonce_str>\n");
        xml.append("<notify_url>https://wxpay.wxutil.com/pub_v2/app/app_pay.php</notify_url>\n");
        xml.append("<out_trade_no>" + outTradeNo + "</out_trade_no>\n");
        xml.append("<spbill_create_ip>192.168.1.1</spbill_create_ip>\n");
        xml.append("<total_fee>1</total_fee>\n");
        xml.append("<trade_type>APP</trade_type>\n");
        xml.append("<sign>" + sign + "</sign>\n");
        xml.append("</xml>");

        try {
            final byte[] xmlbyte = xml.toString().getBytes("UTF-8");

            System.out.println(xml);

            URL url = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");


            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true);// 允许输出
            conn.setDoInput(true);
            conn.setUseCaches(false);// 不使用缓存
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Length",
                    String.valueOf(xmlbyte.length));
            conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
            conn.setRequestProperty("X-ClientType", "2");//发送自定义的头信息


            conn.getOutputStream().write(xmlbyte);
            conn.getOutputStream().flush();
            conn.getOutputStream().close();


            if (conn.getResponseCode() != 200)
                throw new RuntimeException("请求url失败");

            InputStream is = conn.getInputStream();// 获取返回数据


            // 使用输出流来输出字符(可选)
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = is.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            String string = out.toString("UTF-8");
            System.out.println(string);

            Log.e("      微信返回数据   ", "  ---   " + string);
            out.close();

            return string;

        } catch (Exception e) {
            System.out.println(e);
        }
        return "失败";
    }

}
